#include "gadu.h"

Gadu::Gadu(int number, const char* pass, int state, const char* descr){
    WORD wVersionRequested=MAKEWORD(1,0);
    WSADATA wsaData;
    WSAStartup(wVersionRequested, &wsaData);

    info.number = number;
    info.pass = pass;
    info.state = state;
    info.descr = descr;
    info.status = STATE_GG_NOT_CONNECTED;

    WSACleanup();
}

Gadu::~Gadu(){
    gg_logoff(sess);
    gg_free_session(sess);
}

state_gg_t Gadu::login(){
    struct gg_login_params param;

    memset(&param, 0, sizeof(param));
    param.uin = info.number;
    param.password = (char*)info.pass;
    param.async = 0;
    param.status = info.state;
    param.status_descr = (char*)info.descr;

    sess = gg_login(&param);

    if(!sess){
        info.status = STATE_GG_FAIL;
        return STATE_GG_FAIL;
    }

    if(gg_notify(sess, NULL, 0) == -1){
        info.status = STATE_GG_FAIL;
        return STATE_GG_FAIL;
    }

    info.status = STATE_GG_CONNECTED;
    return STATE_GG_CONNECTED;
}

state_gg_t Gadu::logout(){
    info.status = STATE_GG_NOT_CONNECTED;
    gg_logoff(sess);
    gg_free_session(sess);

    return STATE_GG_NOT_CONNECTED;
}

void Gadu::sendMessage(int reciver, const char* text){
    gg_notify(sess, NULL, 0);
    gg_send_message(sess, GG_CLASS_MSG, reciver, (const unsigned char*)text);
}

void Gadu::getMessage(int* sender, const char** text, time_t* _time){
    *sender = events->event.msg.sender;
    *text = (const char*)events->event.msg.message;
    *_time = events->event.msg.time;
}

void Gadu::maintainConnection(){
    initEvents();
    switch(getEvents()){
        case GG_EVENT_CONN_SUCCESS:
            info.status = STATE_GG_CONNECTED;
            break;

        case GG_EVENT_CONN_FAILED:
            info.status = STATE_GG_FAIL;
            break;

        case GG_EVENT_PONG:
            break;

        case GG_EVENT_DISCONNECT:
            info.status = STATE_GG_NOT_CONNECTED;
            break;
    }
    cleanupEvents();

    if(info.status == STATE_GG_FAIL || info.status == STATE_GG_NOT_CONNECTED)
        login();
}
